package com.lbb.springboot.util;

import com.lbb.springboot.entity.dto.ExcelDataDto;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelImportUtils {
    private static FormulaEvaluator evaluator;

    // @描述：是否为2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述：是否为2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    /**
     * 验证EXCEL文件
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath){
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){
            return false;
        }
        return true;
    }

    /**
     * 解析excel文件并将内容返回
     * Map: key代表表格列的索引号（0开始），value对应表格中的内容
     * @param file
     * @return
     */
    public static List<Map<Integer, String>> analysisExcel(MultipartFile file) {
        InputStream is = null;
        Workbook wb = null;
        List<Map<Integer, String>> mapList = null;
        try {
            is = file.getInputStream();
            if (isExcel2003(file.getOriginalFilename())) {
                wb = new HSSFWorkbook(is);
            }else if (isExcel2007(file.getOriginalFilename())) {
                wb = new XSSFWorkbook(is);
            }
//            wb = new XSSFWorkbook(is);
            evaluator=wb.getCreationHelper().createFormulaEvaluator();
            mapList = new ArrayList<>();
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                Sheet sheet = wb.getSheetAt(i);
                if (sheet.getLastRowNum() > 0) {    // getLastRowNum()获取最后的索引号，从0位置开始
                    for (int j = 1; j < sheet.getLastRowNum()+1; j++) { // 第一行是标题行，所以从第二行开始取数据
                        Row row = sheet.getRow(j);
                        Map<Integer, String> map = new HashMap<>();
                        int k = 0;
                        for (; k < row.getLastCellNum(); k++) {
                            map.put(k, getCellValueByCell(row.getCell(k)));
                        }
                        //YHQ 2018-07-25 最后一列增加行号
                        map.put(k,j+"");
                        mapList.add(map);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return mapList;
    }
    
    /**
     * 根据sheetName解析excel（若sheetName不存在，默认取第一个sheet）
     * @param file
     * @param sheetName
     * @return
     */
    public static List<ExcelDataDto> analysisExcelBySheetName(MultipartFile file, String sheetName) {
        InputStream is = null;
        Workbook wb = null;
        List<ExcelDataDto> mapList = null;
        ExcelDataDto excelDataDto = null;
        try {
            is = file.getInputStream();
            if (isExcel2003(file.getOriginalFilename())) {
                wb = new HSSFWorkbook(is);
            }else if (isExcel2007(file.getOriginalFilename())) {
                wb = new XSSFWorkbook(is);
            }
//            wb = new XSSFWorkbook(is);
            evaluator=wb.getCreationHelper().createFormulaEvaluator();
            mapList = new ArrayList<>();
            Sheet sheet=null;
            if(StringUtils.isNotBlank(sheetName)) {
                sheet = wb.getSheet(sheetName);
                if(sheet == null){
                    sheet = wb.getSheetAt(0);
                }
            }
            else {
                sheet = wb.getSheetAt(0);
            }
            if (sheet.getLastRowNum() > 0) {    // getLastRowNum()获取最后的索引号，从0位置开始
                for (int j = 1; j < sheet.getLastRowNum()+1; j++) { // 第一行是标题行，所以从第二行开始取数据
                    Row row = sheet.getRow(j);
                    //跳过空行
                    if(isEmptyRow(row)){
                        continue;
                    }
                    excelDataDto = new ExcelDataDto();
                    Map<Integer, String> map = new HashMap<>();
                    for (int k = 0; k < row.getLastCellNum(); k++) {
                        map.put(k, getCellValueByCell(row.getCell(k)));
                    }
                    excelDataDto.setRowData(map);
                    excelDataDto.setRowNum(j+1);
                    mapList.add(excelDataDto);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return mapList;
    }
    
    /**
     * 获取单元格各类型值，返回字符串类型
     * @param cell
     * @return
     */
    private static String getCellValueByCell(Cell cell) throws Exception {
        //判空，单元格为空返回null
        if(cell == null){
            return null;
        }
        String cellValue = "";
        int cellType = cell.getCellType();
        if(cellType == Cell.CELL_TYPE_FORMULA){ //表达式类型
            cellType = evaluator.evaluate(cell).getCellType();
        }
        switch (cellType) {
            case Cell.CELL_TYPE_STRING: //字符串类型
                cellValue= cell.getStringCellValue().trim();
                cellValue= StringUtils.isEmpty(cellValue) ? "" : cellValue;
                break;
            case Cell.CELL_TYPE_BOOLEAN:  //布尔类型
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_NUMERIC: //数值类型
                if (HSSFDateUtil.isCellDateFormatted(cell)) {  //判断日期类型
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cellValue = sdf.format(cell.getDateCellValue());
                } else {  //否
                    cellValue = new DecimalFormat("#.######").format(cell.getNumericCellValue());
                }
                break;
            default: //其它类型，取空串吧
                cellValue = "";
                break;
        }
        return cellValue.trim();
    }

    /**
     * 判断是否空行
     * @param row
     * @return
     * @throws Exception
     */
    private static Boolean isEmptyRow(Row row) throws Exception {
        if(row == null){
            return true;
        }
        //遍历该行所有列，收集是否有非空的列值
        for (int k = 0; k < row.getLastCellNum(); k++) {
            String value = getCellValueByCell(row.getCell(k));
            if(StringUtils.isNotBlank(value)){
               return false;
            }
        }

        return true;
    }

}
